#encoding=utf8
import sys
import re
import urllib2, urllib
import os

class Music_ID_Picker:
	def __init__(self):
		self.pattern = re.compile(r'http://www.xiami.com/song/(\d+)[?]?.*')
		pass

	def get_music_id(self, link):
		match = re.match(self.pattern, link)
		if match:
			return match.group(1)
		else:
			return -1

class Xiami_downloader:
	def __init__(self):
		self.music_id_picker = Music_ID_Picker()
		self.xmlfile = "http://www.xiami.com/song/playlist/id/%s/object_name/default/object_id/0"

	def download(self, link):
		music_id = self.music_id_picker.get_music_id(link)
		print self.xmlfile % music_id
		content = self.urlopen(self.xmlfile % music_id)
		title, location, lyc, pic = self.extract_xml(content)
		#print "location: " + location
		location = self.decode_location(location)

		print "title: " + title
		print "location: " + location
		print "lyc: " + lyc
		print "pic: " + pic

		content_dir = os.path.join(os.path.dirname("__file__"), title)
		if not os.path.exists(content_dir):
			os.mkdir(content_dir)

		urllib.urlretrieve(location, './%s/%s.mp3' % (title, title))
		urllib.urlretrieve(lyc, './%s/%s' % (title, lyc.replace('/', '.')))
		urllib.urlretrieve(pic, './%s/%s' % (title, pic.replace('/', '.')))


	def urlopen(self, url):

		headers = {
            'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
        }
		request = urllib2.Request(url = url, headers = headers)
		response = urllib2.urlopen(request)
		content = response.read()
		return content

	def extract_xml(self, content):
		title = re.search(r'(<title>)(.+)(<\/title>)', content).group(2)
		location = re.search(r'(<location>)(.+)(<\/location>)', content).group(2)
		lyc = re.search(r'(<lyric>)(.+)(<\/lyric>)', content).group(2) 
		pic = re.search(r'(<pic>)(.+)(<\/pic>)', content).group(2)
		return title, location, lyc, pic

	def decode_location(self, location):
		row = int(location[0])
		a = location[1:len(location)]
		fs = len(a) % row
		col = (len(a) + row - fs) / row

		#print fs
		#print row
		#print col

		b = ""
		for i in range(0, col):
			for j in range(0, row):
				if len(b) < len(a):
					if j < fs:
						index = i + col * j
						if index < len(a):
							b += a[index]
					else:
						index = fs * col + (j - fs) * (col - 1) + i
						if index < len(a):
							b += a[index]
		#print a
		return urllib2.unquote(b).replace('^', '0')


if __name__ == '__main__':
	if len(sys.argv) != 2:
		print "输入链接有误！请重新输入"
	else:
		link = sys.argv[1]
		xiami = Xiami_downloader()
		xiami.download(link)
